import os
from pdf2docx import Converter
import logging
from PyQt5.QtCore import QObject, pyqtSignal

class ConversionSignals(QObject):
    """
    自定义信号类，用于在转换过程中传递进度信息
    """
    progress_updated = pyqtSignal(int)  # 进度信号
    conversion_finished = pyqtSignal(bool, str)  # 转换完成信号

class PDFConverter:
    def __init__(self, log_file='conversion.log'):
        # 配置日志
        logging.basicConfig(
            filename=log_file, 
            level=logging.INFO,
            format='%(asctime)s - %(levelname)s: %(message)s'
        )
        self.logger = logging.getLogger(__name__)
        self.signals = ConversionSignals()

    def convert_single_file(self, pdf_path, docx_path=None):
        """
        转换单个PDF文件到Word，并提供进度信息
        
        :param pdf_path: PDF文件路径
        :param docx_path: 输出Word文件路径，默认为PDF同目录
        :return: 转换是否成功
        """
        try:
            # 如果未指定输出路径，则在PDF同目录生成
            if not docx_path:
                docx_path = os.path.splitext(pdf_path)[0] + '.docx'
            
            # 发送初始进度
            self.signals.progress_updated.emit(10)
            
            # 执行转换
            cv = Converter(pdf_path)
            
            # 获取总页数
            total_pages = len(cv.pages)
            
            # 逐页转换并更新进度
            for page_num, page in enumerate(cv.pages, 1):
                progress = int((page_num / total_pages) * 80) + 10
                self.signals.progress_updated.emit(progress)
            
            # 保存转换结果
            cv.convert(docx_path)
            cv.close()
            
            # 发送最终进度
            self.signals.progress_updated.emit(100)
            
            self.logger.info(f"成功转换 {pdf_path} 到 {docx_path}")
            self.signals.conversion_finished.emit(True, docx_path)
            return True
        
        except Exception as e:
            self.logger.error(f"转换 {pdf_path} 失败: {str(e)}")
            self.signals.progress_updated.emit(0)
            self.signals.conversion_finished.emit(False, str(e))
            return False

    def batch_convert(self, pdf_folder, output_folder=None):
        """
        批量转换PDF文件，并提供总体进度
        
        :param pdf_folder: PDF文件夹路径
        :param output_folder: 输出文件夹，默认为PDF同目录
        :return: 转换成功和失败的文件数
        """
        # 获取PDF文件列表
        pdf_files = [f for f in os.listdir(pdf_folder) if f.lower().endswith('.pdf')]
        total_files = len(pdf_files)
        
        success_count = 0
        fail_count = 0
        
        # 遍历文件夹中的PDF文件
        for index, filename in enumerate(pdf_files, 1):
            pdf_path = os.path.join(pdf_folder, filename)
            
            # 计算总体进度
            overall_progress = int((index / total_files) * 100)
            self.signals.progress_updated.emit(overall_progress)
            
            # 确定输出路径
            if output_folder:
                docx_path = os.path.join(output_folder, os.path.splitext(filename)[0] + '.docx')
            else:
                docx_path = None
            
            # 转换文件
            if self.convert_single_file(pdf_path, docx_path):
                success_count += 1
            else:
                fail_count += 1
        
        self.logger.info(f"批量转换完成：成功{success_count}个，失败{fail_count}个")
        return success_count, fail_count